package wikigearsconnector.actions;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import wikigearsconnector.connect.connector.Connector;
import wikigearsconnector.paramdialog.ParametersDialog;

public class LoadProjectToUpdateSiteAction implements IObjectActionDelegate {

	public final static String CONNECTION_URL = "http://127.0.0.1:80/storeblob/";
	public final static QualifiedName LOGIN_PROP = new QualifiedName(
			"blobloader", "login_pr");
	public final static QualifiedName PASS_PROP = new QualifiedName(
			"blobloader", "passwd_pr");
	public final static QualifiedName HOST_PROP = new QualifiedName(
			"blobloader", "host_pr");
	public final static QualifiedName PORT_PROP = new QualifiedName(
			"blobloader", "port_pr");

	private ISelection selection;

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		return;

	}

	public void run(IAction action) {
		loadFilesToSite(selection);
		return;
	}

	public void selectionChanged(IAction action, ISelection selection) {
		this.selection = selection;

		return;
	}

	private void loadFilesToSite(ISelection selection) {

		if (selection instanceof StructuredSelection) {
			StructuredSelection ss = (StructuredSelection) selection;
			Iterator i = ss.iterator();
			while (i.hasNext()) {
				IProject p = (IProject) i.next();
				// Checking ConnectionParameters

				String l = "";
				String pass = "";
				String h = "";
				String pp = "";
				boolean flg = false;
				do {
					flg = false;
					try {
						l = p.getPersistentProperty(LOGIN_PROP);
						pass = p.getPersistentProperty(PASS_PROP);
						h = p.getPersistentProperty(HOST_PROP);
						pp = p.getPersistentProperty(PORT_PROP);

						int f = checkConnectionParametersForUpdSite(p, h, pp,
								l, pass);
						if ((h == null || pp == null || l == null
								|| pass == null || h.length() == 0
								|| pp.length() == 0 || pass.length() == 0 || l
								.length() == 0)
								&& f < 0) {
							flg = true;
						}
					} catch (CoreException e1) {
						e1.printStackTrace();
					}
				} while (flg);

				final String login = l;
				final String passwd = pass;
				final String host = h;
				final int port = Integer.parseInt(pp);

				int a = 10;
				a = 12;
				final String projName = p.getName();
				final boolean[] status = new boolean[1];
				try {
					p.accept(new IResourceVisitor() {

						public boolean visit(IResource resource)
								throws CoreException {
							try {
								if (!(resource instanceof IProject)
										&& !(resource instanceof IFolder)) {
									final URL url = resource.getLocationURI()
											.toURL();

									final String fName = resource
											.getProjectRelativePath()
											.toOSString();

									Job j = new Job(
											"CommitResource: project name: "
													+ projName + " fileName: "
													+ fName) {

										@Override
										protected IStatus run(
												IProgressMonitor monitor) {
											Connector conn = new Connector(
													host, port, login, passwd,
													projName);
											final IStatus status = conn.init();
											if (status == Status.OK_STATUS) {
												conn.commitResource(url, fName);
												System.out.println("Resource " + fName + " uploaded");
											} else {
												String message = "Resource " + fName + " was not uploaded. ";
												if (status.getException() != null)
													message += "Reason " + status.getException();
												else
													message += "Reason " + status.getMessage();
												final String finalMessage = message;
												Display.getDefault().asyncExec(new Runnable()
												{
													
													public void run()
													{
														ErrorDialog.openError(Display.getDefault().getActiveShell(), "Error uploading resources",finalMessage,status);														
													}
												});

												System.err.println(message);
											}
											return Status.OK_STATUS;
										}

									};
									j.schedule();
								}
							} catch (MalformedURLException e) {
								e.printStackTrace();
							}

							return true;
						}
					});
					
					} catch (CoreException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	private int checkConnectionParametersForUpdSite(IProject project, String h,
			String p, String l, String ps) {
		ParametersDialog pd = new ParametersDialog(Display.getDefault()
				.getActiveShell());
		pd.create();
		pd.setTitle("Connection parameters");
		pd.setMessage("Please enter connection parameters");
		pd.init(l, ps, h, p);
		pd.getShell().setSize(300, 250);
		int flg = pd.open();
		int ret = -1;
		if (flg == Dialog.OK) {
			try {

				String login = pd.getLogin();
				String password = pd.getPassword();
				String host = pd.getHost();
				String port = pd.getPort() + "";

				if (login.length() != 0 && password.length() != 0
						&& host.length() != 0) {
					ret = 0;
				}

				project.setPersistentProperty(LOGIN_PROP, login);
				project.setPersistentProperty(PASS_PROP, password);
				project.setPersistentProperty(HOST_PROP, host);
				project.setPersistentProperty(PORT_PROP, port);
			} catch (CoreException e) {
				e.printStackTrace();
			}
			return ret;
		} else {
			return ret;
		}
	}
}
